package com.tonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tonghe.domain.ResponseResult;
import com.tonghe.domain.dto.EditDemandDTO;
import com.tonghe.domain.entity.Demand;
import com.tonghe.enums.AppHttpCodeEnum;
import com.tonghe.mapper.DemandMapper;
import com.tonghe.utils.BeanCopyUtils;
import com.tonghe.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tonghe.service.DemandService;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Demand)表服务实现类
 *
 * @author tonghe
 * @since 2022-09-09 18:46:53
 */
@Service("demandService")
public class DemandServiceImpl extends ServiceImpl<DemandMapper, Demand> implements DemandService {

    @Autowired
    private DemandMapper demandMapper;

    /** 通过公司id获取该公司需求 */
    @Override
    public ResponseResult selectByRecruitmentId(Integer id) {
        List<Demand> demands = demandMapper.selectByRecruitmentId(id);
        return ResponseResult.okResult(demands);
    }

    /** 增加需求 */
    @Override
    public ResponseResult insertDemand(EditDemandDTO editDemandDTO) {
        // TODO checkPaterIdExist
        Demand demand = BeanCopyUtils.copyBean(editDemandDTO, Demand.class);
        demand.setCreateBy(SecurityUtils.getUserId().intValue());
        demand.setCreateTime(new Date());
        int insert = demandMapper.insert(demand);
        return insert > 0 ? ResponseResult.okResult() : ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }

    /** 获取树形结构 */
    @Override
    public ResponseResult selectTreeDemand() {
        LambdaQueryWrapper<Demand> wrapper = new LambdaQueryWrapper<>();
        // TODO 常量替换
        wrapper.eq(Demand::getStatus, 0);
        List<Demand> demandList = list(wrapper);
        List<Demand> list = buildDemandTree(demandList,0L);

        return ResponseResult.okResult(list);
    }

    private List<Demand> buildDemandTree(List<Demand> demands, long parentId) {
        List<Demand> collect = demands.stream()
                .filter(demand -> demand.getPId().equals(parentId))
                .map(demand -> demand.setChildren(getDemandChildren(demand, demands)))
                .collect(Collectors.toList());
        return collect;
    }

    private List<Demand> getDemandChildren(Demand demand, List<Demand> demands) {
        List<Demand> collect = demands.stream()
                .filter(d -> d.getPId().equals(demand.getId()))
                .map(d -> d.setChildren(getDemandChildren(d, demands)))
                .collect(Collectors.toList());
        return collect;
    }

}
